#include "ClientMgr.h"
#include "DataProc.h"

ClientInfo::~ClientInfo()
{
    if (nullptr != pDataProc)
    {
        delete pDataProc;
        pDataProc = nullptr;
    }
}

CClientMgr::CClientMgr()
{
    m_nIdMax = 0;
}

CClientMgr::~CClientMgr()
{
}

ClntNode *CClientMgr::NewClient(void *pSvr, CClient *pClnt)
{
    ClntNode *pNode = nullptr;

    if (m_lstFree.IsEmpty())
        pNode = m_lstClnt.NewNode();
    else
        pNode = m_lstFree.PopFront();

    if (nullptr != pNode)
    {
        CDataProc *dp = new CDataProc(pNode);

        if (nullptr == dp)
        {
            m_lstFree.PushBack(pNode);
            return nullptr;
        }

        ++m_nIdMax;
        pNode->nId = m_nIdMax;
        pNode->pSvr = pSvr;
        pNode->pClnt = pClnt;
        pNode->pDataProc = dp;
        m_lstClnt.PushBack(pNode);
    }

    return pNode;
}

bool CClientMgr::DeleteClient(ClntNode *pNode)
{
    bool bRet = false;

    if (nullptr == pNode)
        return false;

    if (nullptr != pNode->pDataProc)
    {
        delete pNode->pDataProc;
        pNode->pDataProc = nullptr;
    }

    bRet = m_lstClnt.Remove(pNode);

    if (bRet)
        bRet = m_lstFree.PushBack(pNode);

    return bRet;
}

bool CClientMgr::IsValidNode(ClntNode *pNode)
{
    if (nullptr == pNode)
        return false;

    return (pNode->Belong() == &m_lstClnt);
}